package com.guyaogg.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guyaogg.common.to.SkuHasStockVO;
import com.guyaogg.common.to.mq.OrderTo;
import com.guyaogg.common.to.mq.SeckillOrderTo;
import com.guyaogg.common.utils.PageUtils;
import com.guyaogg.common.utils.Query;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.utils.ToT;
import com.guyaogg.common.vo.MemberRespVO;
import com.guyaogg.gulimall.order.constant.OrderConstant;
import com.guyaogg.gulimall.order.dao.OrderDao;
import com.guyaogg.gulimall.order.dao.OrderItemDao;
import com.guyaogg.gulimall.order.entity.OrderEntity;
import com.guyaogg.gulimall.order.entity.OrderItemEntity;
import com.guyaogg.gulimall.order.entity.PaymentInfoEntity;
import com.guyaogg.gulimall.order.enume.OrderStatusEnum;
import com.guyaogg.gulimall.order.feign.CartFeignService;
import com.guyaogg.gulimall.order.feign.MemberFeignService;
import com.guyaogg.gulimall.order.feign.ProductFeignService;
import com.guyaogg.gulimall.order.feign.WmsFeignService;
import com.guyaogg.gulimall.order.interceptor.LoginUserInterceptor;
import com.guyaogg.gulimall.order.service.OrderItemService;
import com.guyaogg.gulimall.order.service.OrderService;
import com.guyaogg.gulimall.order.service.PaymentInfoService;
import com.guyaogg.gulimall.order.to.OrderCreateTo;
import com.guyaogg.gulimall.order.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {
    private final MemberFeignService memberFeignService;
    private final CartFeignService cartFeignService;
    private final ThreadPoolExecutor executor;
    private final WmsFeignService wmsFeignService;
    private final StringRedisTemplate redisTemplate;
    private final ThreadLocal<OrderSubmitVO> submitVOThreadLocal = new ThreadLocal<>();
    private final ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentInfoService paymentInfoService;


    public OrderServiceImpl(MemberFeignService memberFeignService, CartFeignService cartFeignService, ThreadPoolExecutor executor, WmsFeignService wmsFeignService, StringRedisTemplate redisTemplate, ProductFeignService productFeignService, OrderItemDao orderItemDao) {
        this.memberFeignService = memberFeignService;
        this.cartFeignService = cartFeignService;
        this.executor = executor;
        this.wmsFeignService = wmsFeignService;
        this.redisTemplate = redisTemplate;
        this.productFeignService = productFeignService;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVO confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVO orderConfirmVO = new OrderConfirmVO();

        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            // 共享老数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 1.远程查询所有的收货地址列表
            List<MemberAddressVO> addresses = memberFeignService.getAddresses(memberRespVO.getId());
            orderConfirmVO.setAddresses(addresses);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            // 共享老数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            // 2.远程查询购物车所有选中的购物项
            List<OrderItemVO> items = cartFeignService.getCurrentUserCartItems();
            orderConfirmVO.setItems(items);
        }, executor).thenRunAsync(() -> {
            List<OrderItemVO> items = orderConfirmVO.getItems();
            List<Long> collect = items.stream().map(OrderItemVO::getSkuId).collect(Collectors.toList());
            ToT<List<SkuHasStockVO>> skusHasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuHasStockVO> data = skusHasStock.getData();
            if (data != null && data.size() > 0) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuHasStockVO::getSkuId, SkuHasStockVO::getHasStock));
                orderConfirmVO.setStocks(map);
            }

        }, executor);


        // 3.查询用户积分(优惠等等
        Integer integration = memberRespVO.getIntegration();
        orderConfirmVO.setIntegration(integration);

        // 4.其他数据自动计算


        // TODO 5.防重令牌，幂等性
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVO.getId(), token, 30, TimeUnit.MINUTES);
        orderConfirmVO.setOrderToken(token);

        CompletableFuture.allOf(addressFuture, cartFuture).get();

        log.debug("填充后的数据：{}", orderConfirmVO);

        return orderConfirmVO;
    }

    /**
     * #@Transactional(isolation = Isolation.REPEATABLE_READ) 默认 隔离级别
     * propagation = Propagation.REQUIRED 传播事务级别
     * timeout = -1 超时时间
     * 注意点，spring 执行事务是靠代理完成，统一方法内方法互调，不使用业务对象调，就会绕过代理对象，即方法的事务注解就失效了
     * 失效解决见著启动类注释
     *
     * @param vo
     * @return
     */
//    @GlobalTransactional  不适应于高并发环境，锁太多
    @Transactional(isolation = Isolation.REPEATABLE_READ,
            propagation = Propagation.REQUIRED,
            timeout = -1)
    @Override
    public SubmitOrderResponseVO submitOrder(OrderSubmitVO vo) {
        SubmitOrderResponseVO responseVO = new SubmitOrderResponseVO();
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        // 去创建订单，验令牌，验价格，锁库存
        String orderToken = vo.getOrderToken();
        // 令牌的对比和删除必须保证原子性
        // 脚本返回 0 令牌失败 和 1 删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVO.getId());
//        if(orderToken != null && orderToken.equals(redisToken)){
//            // 令牌验证通过
//
//        }else {
//            // 不通过
//            return  null;
//        }
        // 原子验证和删除
        Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVO.getId()), orderToken);
        if (result == null || 0L == result) {
            // 令牌验证失败,回到原页面
            responseVO.setCode(1);
            return responseVO;
        }
        submitVOThreadLocal.set(vo);
        // 1.创建订单
        OrderCreateTo order = createOrder();
        submitVOThreadLocal.remove();

        // 2.验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal payPrice = vo.getPayPrice();
        log.debug("vo:{},real:{}", payPrice, payAmount);
        double deviation = 0.01;
        double abs = Math.abs(payAmount.subtract(payPrice).doubleValue());
        if (abs >= deviation) {
            // 验价失败
            log.debug("验价失败,验价误差:{}", abs);
            responseVO.setCode(2);
            return responseVO;
        }
        // 3.保存订单
        saveOrder(order);
        // 4.库存锁定,只要有异常回滚订单数据
        WareSkuLockVO lockVO = new WareSkuLockVO();
        lockVO.setOrderSn(order.getOrder().getOrderSn());

        List<OrderItemVO> orderItemVOs = order.getOrderItems().stream().map(item -> {
            OrderItemVO orderItemVO = new OrderItemVO();
            orderItemVO.setSkuId(item.getSkuId());
            orderItemVO.setCount(item.getSkuQuantity());
            orderItemVO.setTitle(item.getSkuName());
            return orderItemVO;
        }).collect(Collectors.toList());
        lockVO.setLocks(orderItemVOs);

        // 为了分布式事务保证高并发。库存服务自己回滚。可以发消息给库存服务
        // 库存服务本身也可以使用自动解锁模式   使用消息队列完成这件事情
        R r = wmsFeignService.orderLockStock(lockVO);

        if (r.getCode() != 0) {
            // TODO 分布式回滚，异常机制传递不到远程服务事务.还有假失败问题
            // 锁定失败
//            throw new NoStockException(order.getOrder().getId());
            responseVO.setCode(3);
            return responseVO;
        }

        responseVO.setOrder(order.getOrder());
        // TODO 订单创建成功，发送消息给 MQ
        rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());
        // 5.远程扣减积分,模拟失败
//        int i = 10 / 0;
        responseVO.setCode(0);
        return responseVO;
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));

    }

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void closeOrder(OrderEntity order) {
        // 查询当前订单状态
        OrderEntity orderEntity = this.getById(order.getId());
        if (Objects.equals(orderEntity.getStatus(), OrderStatusEnum.CREATE_NEW.getCode())) {
            // 关单
            OrderEntity update = new OrderEntity();
            update.setId(orderEntity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            // 发给 mq 一个
            try {
                // TODO 保证消息一定会发送出去，每一个消息做好日志记录（给数据库保存详细消息）。
                // TODO 定期扫描数据库将失败的消息再发送一遍
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);

            }catch (Exception e){
                // TODO 将没发送成功的消息进行重新发送。

            }
        }
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        // 订单号
        payVo.setOut_trade_no(order.getOrderSn());
        // 订单主题
        List<OrderItemEntity> items = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity orderItem = items.get(0);
        payVo.setSubject(orderItem.getSkuName());
        // 订单金额
        BigDecimal bigDecimal = order.getTotalAmount().setScale(2, RoundingMode.UP);
        payVo.setTotal_amount(bigDecimal.toString());
        // 订单备注
        payVo.setBody(orderItem.getSkuAttrsVals());

        return payVo;

    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVO.getId()).orderByDesc("id")
        );
        List<OrderEntity> collect = page.getRecords().stream().peek(order -> {
            List<OrderItemEntity> items = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(items);
        }).collect(Collectors.toList());
        page.setRecords(collect);

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public String handlePayResult(PayAsyncVo vo) {
        // 保存交易流水
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setAlipayTradeNo(vo.getTrade_no());
        paymentInfo.setOrderSn(vo.getOut_trade_no());
        paymentInfo.setPaymentStatus(vo.getTrade_status());
        paymentInfo.setCallbackTime(vo.getNotify_time());
        paymentInfoService.save(paymentInfo);

        // 修改订单状态信息
        if ("TRADE_SUCCESS".equals(vo.getTrade_status())|| "TRADE_FINISHED".equals(vo.getTrade_status())) {
            // 支付成功，状态
            String orderSn = vo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }

        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
        // TODO 保存订单信息
        OrderEntity order = new OrderEntity();
        order.setOrderSn(seckillOrder.getOrderSn());
        order.setMemberId(seckillOrder.getMemberId());

        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal(seckillOrder.getNum().toString()));
        order.setPayAmount(multiply);
        this.save(order);
        // TODO 保持订单项
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderId(order.getId());
        orderItem.setOrderSn(seckillOrder.getOrderSn());
        orderItem.setRealAmount(multiply);
        orderItem.setSkuQuantity(seckillOrder.getNum());
        // TODO 订单项详细信息远程调用。。。
        orderItemService.save(orderItem);

    }

    /**
     * 保存订单数据
     *
     * @param order
     */
    private void saveOrder(OrderCreateTo order) {
        // 订单保存
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        // 保存所有订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);


    }

    /**
     * 生成创建订单
     *
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 1.创建基础订单
        OrderEntity order = buildOrder();

        // 2.获取所有的订单项
        List<OrderItemEntity> orderItems = buildOrderItems(order.getOrderSn());

        // 3.验价(计算价格相关
        if (orderItems != null) {
            computePrice(order, orderItems);
        }
        createTo.setOrder(order);
        createTo.setOrderItems(orderItems);


        return createTo;
    }

    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItems) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        Integer gift = 0;
        Integer growth = 0;

        // 订单的总额，叠加每一项的总额信息
        for (OrderItemEntity orderItem : orderItems) {
            BigDecimal realAmount = orderItem.getRealAmount();
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            total = total.add(realAmount);
            gift += orderItem.getGiftIntegration();
            growth += orderItem.getGiftGrowth();

        }
        // 1.订单相关数据
        // 价格、优惠
        order.setTotalAmount(total);
        order.setPayAmount(total.add(order.getFreightAmount()));
        order.setPromotionAmount(promotion);
        order.setCouponAmount(coupon);
        order.setIntegrationAmount(integration);
        // 积分信息
        order.setIntegration(gift);
        order.setGrowth(growth);
    }

    private OrderEntity buildOrder() {
        OrderEntity order = new OrderEntity();

        // 会员信息
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();
        order.setMemberId(memberRespVO.getId());
        // 订单号
        String orderSn = IdWorker.getTimeId();
        order.setOrderSn(orderSn);
        OrderSubmitVO submitVO = submitVOThreadLocal.get();
        // 运费，收货地址...
        R r = wmsFeignService.getFare(submitVO.getAddrId());
        FareVO fareResp = r.getData(new TypeReference<FareVO>() {
        });
        order.setFreightAmount(fareResp.getFare());
        order.setReceiverCity(fareResp.getAddress().getCity());
        order.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        order.setReceiverName(fareResp.getAddress().getName());
        order.setReceiverPhone(fareResp.getAddress().getPhone());
        order.setReceiverPostCode(fareResp.getAddress().getPostCode());
        order.setReceiverProvince(fareResp.getAddress().getProvince());
        order.setReceiverRegion(fareResp.getAddress().getRegion());

        // 订单相关状态
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // TODO 这个默认确定收货天数是不是一个发货时候设置
        order.setAutoConfirmDay(7);

        return order;
    }

    /**
     * 构建所有订单项信息
     *
     * @param orderSn 订单号
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每个购物项的价格
        List<OrderItemVO> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            return currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItem = buildOrderItem(cartItem);
                // 订单信息：订单号
                orderItem.setOrderSn(orderSn);

                return orderItem;
            }).collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 构建某一个指定的订单项
     *
     * @param cartItem
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVO cartItem) {
        OrderItemEntity orderItem = new OrderItemEntity();
        // 商品的 SPU 信息
        R r = productFeignService.getSpuInfoBySkuId(cartItem.getSkuId());
        SpuInfo data = r.getData(new TypeReference<SpuInfo>() {
        });
        orderItem.setSpuId(data.getId());
        orderItem.setSpuBrand(data.getBrandId().toString());
        orderItem.setSpuName(data.getSpuName());
        orderItem.setCategoryId(data.getCatalogId());

        // 商品的 SKU 信息
        orderItem.setSkuName(cartItem.getTitle());
        orderItem.setSkuId(cartItem.getSkuId());
        orderItem.setSkuPic(cartItem.getImage());
        orderItem.setSkuPrice(cartItem.getPrice());
        String skuAttrsVales = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItem.setSkuAttrsVals(skuAttrsVales);
        orderItem.setSkuQuantity(cartItem.getCount());
        // TODO 构建某一个指定的订单项优惠信息
        // 积分信息
        orderItem.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItem.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        // TODO 订单项的价格信息
        orderItem.setPromotionAmount(new BigDecimal("0"));
        orderItem.setCouponAmount(new BigDecimal("0"));
        orderItem.setIntegrationAmount(new BigDecimal("0"));
        // 当前订单项的实际金额,原始价格 - 各种优惠
        BigDecimal origin = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        BigDecimal realAmount = origin.subtract(orderItem.getCouponAmount())
                .subtract(orderItem.getPromotionAmount())
                .subtract(orderItem.getIntegrationAmount());
        orderItem.setRealAmount(realAmount);
        return orderItem;
    }

}